package com.basicactivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;

import com.squareup.okhttp.OkHttp;

import org.simple.eventbus.EventBus;


/**
 * oushuhua
 */
public class BasicActivity extends FragmentActivity {
    public final String TAG = toString();
    public Context mBaseContext;
    /**
     * 是否开启eventbus，默认关闭；打开后无法关闭，会在类销毁时自动关闭
     */
    private boolean enableEventBus = false;
    protected static final String EXITAPP = "exit_app";
    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if (action.equals(EXITAPP)) {
                BasicActivity.this.finish();
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBaseContext = this;
        IntentFilter intent = new IntentFilter(EXITAPP);
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(receiver, intent);

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 参数tag不要动，必须为toString()
        LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(receiver);
        if (enableEventBus) {
            EventBus.getDefault().unregister(this);
        }
        OkHttp.cancelAll(TAG);
    }

    public void openEventBus() {
        this.enableEventBus = true;
        EventBus.getDefault().register(this);
    }

    /**
     * 部分页面加载数据出错展示加载失败页
     * 顶部按钮条的操作事件需要全部传回给该页面
     * 此时设置标题时需要使用此方法
     * 参见RefreshTest.class使用方法
     * @param view
     */
    public void setTitleHolder(View view) {}

    //BaseActivity
    public <T extends View> T $(@IdRes int resId){
        return (T)super.findViewById(resId);
    }


}
